package cc.ok200.muzhi;

import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class PluginActivity extends AppCompatActivity {

    private static final String TAG = "PluginActivity";
    private TextView toolbarTitle;
    private LinearLayout contentContainer;
    private Button btnStart;
    private LayoutInflater inflater;
    
    // 插件数据
    private String pluginType;
    private String pluginName;
    private String pluginDescription;
    private String pluginLogo;
    private String pluginNickname;
    private JSONArray pluginViews;
    
    // 存储所有输入控件的引用，用于获取用户输入
    private Map<String, View> inputControls = new HashMap<>();
    private Map<String, EditText> rangeMaxInputs = new HashMap<>(); // 存储range类型的最大值输入框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置沉浸式状态栏，使状态栏与应用主题色一致
        setImmersiveStatusBar();
        
        setContentView(R.layout.activity_plugin);
        inflater = LayoutInflater.from(this);

        // 获取传递过来的插件数据
        if (getIntent().hasExtra("plugin")) {
            pluginType = getIntent().getStringExtra("plugin_type");
            pluginName = getIntent().getStringExtra("plugin_name");
            pluginDescription = getIntent().getStringExtra("plugin_description");
            pluginLogo = getIntent().getStringExtra("plugin_logo");
            pluginNickname = getIntent().getStringExtra("plugin_nickname");
            
            try {
                String viewsJson = getIntent().getStringExtra("plugin_views");
                pluginViews = new JSONArray(viewsJson);
            } catch (JSONException e) {
                Log.e(TAG, "解析views JSON错误: " + e.getMessage());
                Toast.makeText(this, "插件数据错误", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            Toast.makeText(this, "未找到插件数据", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图
        initViews();
        
        // 设置工具栏标题
        toolbarTitle.setText(pluginName);
        
        // 仅渲染views中定义的视图
        renderPluginViews();
        
        // 设置开始按钮点击事件
        btnStart.setOnClickListener(v -> {
            // 收集用户输入
            JSONObject inputs = collectUserInputs();
            if (inputs != null) {
                Toast.makeText(PluginActivity.this, 
                        "开始运行: " + pluginName, 
                        Toast.LENGTH_SHORT).show();
                // 这里实现插件运行的具体逻辑
            }
        });
    }
    
    /**
     * 设置沉浸式状态栏，使状态栏颜色与应用主题色一致
     */
    private void setImmersiveStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            // 设置状态栏绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            // 状态栏透明
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
            
            // 布局内容扩展到状态栏
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            
            // 对于Android 6.0及以上版本，可以设置状态栏文字颜色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 如果主题色较深，状态栏文字使用白色
                // 如果需要黑色文字，则添加 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            }
        }
    }
    
    private void initViews() {
        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar_plugin);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        // 获取视图引用
        toolbarTitle = findViewById(R.id.toolbar_plugin_title);
        contentContainer = findViewById(R.id.content_container);
        btnStart = findViewById(R.id.btn_start);
        
        // 设置返回按钮
        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> onBackPressed());
        
        // 设置昵称显示
        TextView tvNickname = findViewById(R.id.tv_plugin_nickname);
        if (pluginNickname != null && !pluginNickname.isEmpty()) {
            tvNickname.setText("创作者：" + pluginNickname);
            tvNickname.setVisibility(View.VISIBLE);
        } else {
            tvNickname.setVisibility(View.GONE);
        }
    }
    
    private void renderPluginViews() {
        // 清空容器
        contentContainer.removeAllViews();
        
        if (pluginViews == null || pluginViews.length() == 0) {
            return;
        }
        
        try {
            // 解析并渲染JSON格式的视图定义
            for (int i = 0; i < pluginViews.length(); i++) {
                JSONObject viewObj = pluginViews.getJSONObject(i);
                String type = viewObj.getString("type");
                
                switch (type) {
                    case "single_input":
                        addSingleInputView(viewObj);
                        break;
                    case "multi_input":
                        addMultiInputView(viewObj);
                        break;
                    case "range":
                        addRangeInputView(viewObj);
                        break;
                    case "seek_bar":
                        addSeekBarView(viewObj);
                        break;
                    case "integer":
                        addIntegerView(viewObj);
                        break;
                    default:
                        break;
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "解析插件视图错误: " + e.getMessage());
            Toast.makeText(this, "插件视图错误", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 创建带红色星号的标签文本
    private SpannableString createLabelWithStar(String labelText) {
        SpannableString spannableString = new SpannableString("* " + labelText);
        ForegroundColorSpan redColorSpan = new ForegroundColorSpan(
                ContextCompat.getColor(this, android.R.color.holo_red_light));
        spannableString.setSpan(redColorSpan, 
                0, 
                1, 
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
    
    private void addSingleInputView(JSONObject viewObj) throws JSONException {
        String name = viewObj.getString("name");
        String description = viewObj.optString("description", "");
        String defaultValue = viewObj.optString("value", "");
        String id = viewObj.optString("id", name.replace(" ", "_").toLowerCase());
        
        // 加载单行输入视图布局
        View view = inflater.inflate(R.layout.view_single_input, contentContainer, false);
        
        // 设置标签
        TextView labelView = view.findViewById(R.id.tv_label);
        labelView.setText(createLabelWithStar(name));
        
        // 设置描述
        TextView descView = view.findViewById(R.id.tv_description);
        if (!description.isEmpty()) {
            descView.setText(description);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }
        
        // 设置输入框
        EditText inputView = view.findViewById(R.id.et_input);
        inputView.setHint("请输入" + name);
        if (defaultValue != null && !defaultValue.equals("null")) {
            inputView.setText(defaultValue);
        }
        
        // 添加到容器
        contentContainer.addView(view);
        
        // 存储输入控件的引用
        inputControls.put(id, inputView);
    }
    
    private void addMultiInputView(JSONObject viewObj) throws JSONException {
        String name = viewObj.getString("name");
        String description = viewObj.optString("description", "");
        String defaultValue = viewObj.optString("value", "");
        String id = viewObj.optString("id", name.replace(" ", "_").toLowerCase());
        
        // 加载多行输入视图布局
        View view = inflater.inflate(R.layout.view_multi_input, contentContainer, false);
        
        // 设置标签
        TextView labelView = view.findViewById(R.id.tv_label);
        labelView.setText(createLabelWithStar(name));
        
        // 设置描述
        TextView descView = view.findViewById(R.id.tv_description);
        if (!description.isEmpty()) {
            descView.setText(description);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }
        
        // 设置输入框
        EditText inputView = view.findViewById(R.id.et_input);
        inputView.setHint("请输入" + name);
        if (defaultValue != null && !defaultValue.equals("null")) {
            inputView.setText(defaultValue);
        }
        
        // 添加到容器
        contentContainer.addView(view);
        
        // 存储输入控件的引用
        inputControls.put(id, inputView);
    }
    
    private void addRangeInputView(JSONObject viewObj) throws JSONException {
        String name = viewObj.getString("name");
        String description = viewObj.optString("description", "");
        int minValue = viewObj.optInt("min", 0);
        int maxValue = viewObj.optInt("max", 100);
        int defaultValue = viewObj.optInt("defaultValue", minValue);
        String id = viewObj.optString("id", name.replace(" ", "_").toLowerCase());
        
        // 加载范围输入视图布局
        View view = inflater.inflate(R.layout.view_range_input, contentContainer, false);
        
        // 设置标签
        TextView labelView = view.findViewById(R.id.tv_label);
        labelView.setText(createLabelWithStar(name));
        
        // 设置描述
        TextView descView = view.findViewById(R.id.tv_description);
        if (!description.isEmpty()) {
            descView.setText(description);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }
        
        // 设置最小值输入框
        EditText minInput = view.findViewById(R.id.et_min);
        minInput.setText(String.valueOf(defaultValue));
        
        // 设置最大值输入框
        EditText maxInput = view.findViewById(R.id.et_max);
        maxInput.setText(String.valueOf(maxValue));
        
        // 添加到容器
        contentContainer.addView(view);
        
        // 存储输入控件的引用
        inputControls.put(id, minInput); // 存储最小值输入框引用
        rangeMaxInputs.put(id, maxInput); // 存储最大值输入框引用
    }
    
    private void addSeekBarView(JSONObject viewObj) throws JSONException {
        String name = viewObj.getString("name");
        String description = viewObj.optString("description", "");
        int defaultValue = viewObj.optInt("value", 0);
        int max = viewObj.optInt("max", 100);
        String id = viewObj.optString("id", name.replace(" ", "_").toLowerCase());
        
        // 加载滑动条视图布局
        View view = inflater.inflate(R.layout.view_seek_bar, contentContainer, false);
        
        // 设置标签
        TextView labelView = view.findViewById(R.id.tv_label);
        labelView.setText(createLabelWithStar(name));
        
        // 设置描述
        TextView descView = view.findViewById(R.id.tv_description);
        if (!description.isEmpty()) {
            descView.setText(description);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }
        
        // 设置值显示
        TextView valueView = view.findViewById(R.id.tv_value);
        valueView.setText(defaultValue + "%");
        
        // 设置滑动条
        SeekBar seekBar = view.findViewById(R.id.seek_bar);
        seekBar.setMax(max);
        seekBar.setProgress(defaultValue);
        
        // 设置滑动条监听
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                valueView.setText(progress + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 不需要实现
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 不需要实现
            }
        });
        
        // 添加到容器
        contentContainer.addView(view);
        
        // 存储输入控件的引用
        inputControls.put(id, seekBar);
    }
    
    private void addIntegerView(JSONObject viewObj) throws JSONException {
        String name = viewObj.getString("name");
        String description = viewObj.optString("description", "");
        int defaultValue = viewObj.optInt("value", 0);
        String id = viewObj.optString("id", name.replace(" ", "_").toLowerCase());
        
        // 加载整数输入视图布局
        View view = inflater.inflate(R.layout.view_integer, contentContainer, false);
        
        // 设置标签
        TextView labelView = view.findViewById(R.id.tv_label);
        labelView.setText(createLabelWithStar(name));
        
        // 设置描述
        TextView descView = view.findViewById(R.id.tv_description);
        if (!description.isEmpty()) {
            descView.setText(description);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }
        
        // 设置输入框
        EditText inputView = view.findViewById(R.id.et_integer);
        inputView.setHint("请输入" + name);
        inputView.setText(String.valueOf(defaultValue));
        
        // 添加到容器
        contentContainer.addView(view);
        
        // 存储输入控件的引用
        inputControls.put(id, inputView);
    }
    
    private JSONObject collectUserInputs() {
        // 收集用户输入的数据，可以在这里处理并传递给插件执行逻辑
        JSONObject inputData = new JSONObject();
        
        try {
            for (Map.Entry<String, View> entry : inputControls.entrySet()) {
                String id = entry.getKey();
                View view = entry.getValue();
                
                if (view instanceof EditText) {
                    EditText editText = (EditText) view;
                    // 判断是否是range类型的最小值输入框
                    if (rangeMaxInputs.containsKey(id)) {
                        String minValue = editText.getText().toString();
                        String maxValue = rangeMaxInputs.get(id).getText().toString();
                        
                        // 验证输入
                        if (minValue.isEmpty() || maxValue.isEmpty()) {
                            Toast.makeText(this, "请输入完整的范围值", Toast.LENGTH_SHORT).show();
                            return null;
                        }
                        
                        try {
                            // 创建包含min和max的对象
                            JSONObject rangeValue = new JSONObject();
                            rangeValue.put("min", Integer.parseInt(minValue));
                            rangeValue.put("max", Integer.parseInt(maxValue));
                            inputData.put(id, rangeValue);
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                            return null;
                        }
                    } else {
                        String value = editText.getText().toString();
                        if (value.isEmpty()) {
                            Toast.makeText(this, "请输入所有必填项", Toast.LENGTH_SHORT).show();
                            return null;
                        }
                        
                        // 对于整数输入框，转换为整数
                        if (editText.getInputType() == (android.text.InputType.TYPE_CLASS_NUMBER)) {
                            try {
                                inputData.put(id, Integer.parseInt(value));
                            } catch (NumberFormatException e) {
                                Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                                return null;
                            }
                        } else {
                            inputData.put(id, value);
                        }
                    }
                } else if (view instanceof SeekBar) {
                    SeekBar seekBar = (SeekBar) view;
                    inputData.put(id, seekBar.getProgress());
                }
            }
            
            return inputData;
            
        } catch (JSONException e) {
            Log.e(TAG, "处理输入数据错误: " + e.getMessage());
            Toast.makeText(this, "处理输入数据时出错", Toast.LENGTH_SHORT).show();
            return null;
        }
    }
} 